package cn.schoolwow.quickdao.module.database.dml.json.flow.common.check;

import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CheckUniqueFieldNameFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);

        if(manipulationOption.uniqueFieldNames.isEmpty()){
            throw new IllegalArgumentException("请先调用uniqueFieldNames方法指定唯一性约束字段!");
        }
        if(flowContext.containKey("instance")){
            JSONObject instance = (JSONObject) flowContext.checkData("instance");
            for(String uniqueFieldName:manipulationOption.uniqueFieldNames){
                if(!instance.containsKey(uniqueFieldName)){
                    throw new IllegalArgumentException("JSONObject对象不存在键为["+uniqueFieldName+"]的属性!");
                }
            }
        }
        if(flowContext.containKey("instances")){
            JSONArray instances = (JSONArray) flowContext.checkData("instances");
            for(String uniqueFieldName:manipulationOption.uniqueFieldNames){
                for(int i=0;i<instances.size();i++){
                    JSONObject instance = instances.getJSONObject(i);
                    if(!instance.containsKey(uniqueFieldName)){
                        throw new IllegalArgumentException("JSONObject对象不存在键为["+uniqueFieldName+"]的属性!");
                    }
                }
            }
        }
    }

    @Override
    public String name() {
        return "检查是否设置唯一字段列表";
    }
}
